import OSS from 'ali-oss';
import fs from 'fs/promises';
import fsSync from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import Core from "@alicloud/pop-core";

const cdnClient = new Core({
    accessKeyId: "LTAI4G6jvMQdzu2rrPUfT3xG",
    accessKeySecret: "TGRsQNLuRMwDGWdt0sS6QfHpEnn2PV",
    endpoint: "https://cdn.aliyuncs.com",
    apiVersion: "2018-05-10",
});

// 解决ES模块中__dirname的问题
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// 配置信息 - 请替换为你的实际信息
const config = {
    oss: {
        region: 'oss-cn-zhangjiakou', // 例如：oss-cn-beijing
        accessKeyId: 'LTAI4G6jvMQdzu2rrPUfT3xG',
        accessKeySecret: 'TGRsQNLuRMwDGWdt0sS6QfHpEnn2PV',
        bucket: 'bbt-baojing'
    },
    cdn: {
        accessKeyId: 'LTAI4G6jvMQdzu2rrPUfT3xG', // 通常与OSS相同
        accessKeySecret: 'TGRsQNLuRMwDGWdt0sS6QfHpEnn2PV',
        domain: 'baojing.baobeituan.com' // 例如：cdn.example.com
    },
    localDir: path.resolve(__dirname, '../dist'), // 上一级的dist目录
    targetDir: '' // OSS目标路径
};

// 初始化OSS客户端
const ossClient = new OSS({
    region: config.oss.region,
    accessKeyId: config.oss.accessKeyId,
    accessKeySecret: config.oss.accessKeySecret,
    bucket: config.oss.bucket
});

// 递归上传目录
async function uploadDir(localPath, ossPath) {
    try {
        if (!fsSync.existsSync(localPath)) {
            console.error(`错误：目录不存在 - ${localPath}`);
            return false;
        }

        const files = await fs.readdir(localPath, { withFileTypes: true });
        for (const file of files) {
            const localFilePath = path.join(localPath, file.name);
            let ossFilePath = ossPath ? `${ossPath}/${file.name}` : file.name;

            if (file.isDirectory()) {
                await uploadDir(localFilePath, ossFilePath);
            } else {
                console.log(`正在上传: ${localFilePath} -> ${ossFilePath}`);
                const content = fsSync.readFileSync(localFilePath);
                await ossClient.put(ossFilePath, content);
                console.log(`上传成功: ${ossFilePath}`);
            }
        }
        return true;
    } catch (e) {
        console.error('上传失败:', e);
        return false;
    }
}

// 刷新CDN缓存
async function refreshCdnCache(urls) {
    const params = {
        RegionId: "cn-zhangjiakou",
        ObjectPath: urls.join('\n')
    };

    const requestOption = {
        method: "POST",
    };

    const refreshResponse = await cdnClient.request("RefreshObjectCaches", params, requestOption);
    if (refreshResponse.RefreshTaskId){
        console.log("刷新CDN成功", urls);
    }
}

// 主函数
async function main() {
    // 1. 上传文件到OSS
    const uploadSuccess = await uploadDir(config.localDir, config.targetDir);
    if (!uploadSuccess) {
        console.log('上传失败，终止流程');
        return;
    }

    // 2. 准备需要刷新的CDN URL
    // 这里可以根据实际需求调整需要刷新的路径
    const urlsToRefresh = [
        `https://${config.cdn.domain}/`, // 刷新根目录
        `https://${config.cdn.domain}/index.html` // 刷新首页
        // 可以添加更多需要刷新的URL
    ];

    // 3. 刷新CDN缓存
    await refreshCdnCache(urlsToRefresh);

    console.log("发布完成!");
}

// 执行主函数
main();
